#include "EventLoopThreadPool.h"

EventLoopThreadPool::EventLoopThreadPool(EventLoop *baseloop, const std::string name)
    : baseLoop_(baseloop)
    , name_(name)
    , started_(false)
    , threadNums_(0)
    , next_(0)
{

}

EventLoopThreadPool::~EventLoopThreadPool(){
    //不需要释放loop对象，因为loop对象是在栈上申请的
}

void EventLoopThreadPool::start(const ThreadInitCallback& cb){
    //1.标志启动
    started_ = true;
    //2.创建ThreadNums个EventLoop对象，并将其放入对应容器
    for(int i = 0; i < threadNums_; i++){
        char buf[sizeof(name_) + 32];
        snprintf(buf, sizeof(buf), "%s%d", name_.c_str(), i);
        EventLoopThread* eveLoopThread  = new EventLoopThread(cb, buf);
        threads_.push_back(std::unique_ptr<EventLoopThread>(eveLoopThread));
        loops_.push_back(eveLoopThread->startLoop());
    }
    //3.如果是单Reactor，也就是只有一个baseLoop_，那就启动baseloop_
    if(threadNums_ == 0 && cb){
        cb(baseLoop_);
    }
}

EventLoop* EventLoopThreadPool::getNextLoop(){
    if(loops_.empty()){
        return baseLoop_;
    }
    else{
        EventLoop *loop = loops_[next_++];
        if(next_ >= threadNums_){
            next_ = 0;
        }
        return loop;
    }
}

std::vector<EventLoop*> EventLoopThreadPool::getAllLoops(){
    //这里也要判断一下是不是单Reactor
    if(loops_.empty()){
        return std::vector<EventLoop*>(1, baseLoop_);
    }
    else{
        return loops_;
    }
}